package io.litchi.auth.Infrastructure.config.jpa;

import io.litchi.auth.Infrastructure.securityentity.LitchiUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * Jpa自动审计获取当前用户
 *
 * @author helang
 * @since 2025-09-18
 */
@Component
@Slf4j
public class AuditorAwareImpl implements AuditorAware<Long> {

    @Override
    public Optional<Long> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return Optional.empty();
        }
        log.info("Principal type: {}, value: {}",
                authentication.getPrincipal().getClass().getSimpleName(),
                authentication.getPrincipal()
        );
        Object principal = authentication.getPrincipal();
        if (principal instanceof LitchiUser userDetails) {
            return Optional.ofNullable(userDetails.getId());
        }
        return Optional.empty();
    }
}